﻿using JustCleanIt.Common;
using JustCleanIt.DataStructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;

namespace JustCleanIt.Database
{
    public class XmlDatabaseManager : IDatabaseManager
    {
        private static LogManager myLogger = LogManager.GetLogger(typeof(XmlDatabaseManager));

        public bool Save(List<Customer> allCustomers)
        {
            bool result = false;

            try
            {
                Customers customers = new Customers();
                customers.AllCustomers = allCustomers;

                result = ObjectFormatter.SerializeObject<Customers>(customers, Constants.XML_DATABASE_FILE_PATH);
            }
            catch (Exception ex)
            {
                result = false;
                myLogger.LogException("Error while saving customer collection", ex);
            }

            return result;
        }

        public List<Customer> Load()
        {
            List<Customer> allCustomers = new List<Customer>();

            try
            {
                Uri xmlFilePath = new Uri(Constants.XML_DATABASE_FILE_PATH);
                Customers customers = ObjectFormatter.DeserializeObject<Customers>(xmlFilePath);
                allCustomers = customers.AllCustomers;
            }
            catch (Exception ex)
            {
                allCustomers = new List<Customer>();
                myLogger.LogException("Error while loading customer collection", ex);
            }

            return allCustomers;
        }
    }

    [DataContract]
    public class Customers
    {
        [DataMember]
        public List<Customer> AllCustomers { get; set; }
    }
}
